package top.resty.erp.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.resty.erp.domain.Manager;
import top.resty.erp.service.ManagerService;
import top.resty.erp.util.LayuiJson;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/manager")
public class ManagerController {
	
	@Autowired
	private ManagerService managerService;
	
	@RequestMapping("/findManagerByRealName")
	@ResponseBody
	public Manager findManagerByRealName(String realName){
		return managerService.findManagerByRealName(realName);
	}
	
	
	@RequestMapping("/update")
	@ResponseBody
	public String updateManager(String keyStr ,String valueStr , Integer id){
		switch (keyStr){
			case "userName": keyStr = "user_name";break;
			case "realName": keyStr = "real_name";break;
			default:break;
		}
		System.out.println(keyStr + "====" + valueStr + "=====" + id);
		if(managerService.updateManager(keyStr, valueStr, id) == 1){
			return "成功";
		}
		return "失败";
	}
	
	
	@RequestMapping("/name")
	@ResponseBody
	public boolean getManagerName(String userName){
		return managerService.getName(userName);
	}
	
	
	@RequestMapping("/del")
	@ResponseBody
	public String delManager(Integer index){
		System.out.println(index);
		managerService.delManager(index);
		return "success";
	}
	
	@PutMapping("/login")
	@ResponseBody
	public Manager getUser(Manager manager, HttpServletRequest req){
		Manager userForNameAndPassword = managerService.getUserForNameAndPassword(manager);
		if(userForNameAndPassword!=null){
			req.getSession().setAttribute("manager", userForNameAndPassword);
			return  userForNameAndPassword;
		}
		return null;
	}
	
	
	
	@GetMapping("/manList")
	@ResponseBody
	public LayuiJson<Manager> goManagerListPage(int page,int limit) {
		Page<Manager> objectPage = PageHelper.startPage(page, limit);
		
		List<Manager> list = managerService.getManagers();
		
		LayuiJson<Manager> layuiJson = new LayuiJson<Manager>();
		layuiJson.setCount((int) objectPage.getTotal());
		layuiJson.setData(list);
		return layuiJson;
	}
	
	@RequestMapping("/save")
	public String addManager(Manager manager){
		//todo:对密码进行加密
		if(manager.getRole()==null){
			manager.setRole(1);
		}
		int i = managerService.saveManager(manager);
		if (i==1){
			return "man/manager_list";
		}
		return "man/manager_add_fail";
	}
	
	
	/**页面跳转**/
	@GetMapping("/add")
	public String goManagerAddPage(){
		return "man/manager_add";
	}
	
	@RequestMapping("/list")
	public String goManagerListPage(){
		return "man/manager_list";
		// return "man/manager_add";
	}
	
}
